<template>
	<view class="bg vh-100 box-sizing">
		<view :style="`padding-top:${height}px;`" class="pl-24">
			<text class="text-white fw-600 fs-20">艺术二维码</text>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<view v-if="WEBCONFIG?.weixin_video_status && WEBCONFIG?.weixin_video_status == 1">
			<ad :unit-id="WEBCONFIG?.weixin_video_ad_id" ad-theme="white"></ad>
		</view>
		<!-- #endif -->
		<view class="py-10 px-20 mt-10 fw-bold" style="background-color: rgba(0, 0, 0, 0.30);">
			<y-notice :text='WEBCONFIG?.notice' color='#fff' size='15px'>
				<block #left>
				<image src="@/static/icon/gg.png" style="width: 69px;height: 19px;"  ></image>
				</block>
			</y-notice>
		</view>
		<view class="flex flex-column grid-gap-15 px-12 mt-16" style="padding-bottom: var(--window-bottom);">
			<y-setup v-model="form.type" @change="change"></y-setup>
			<view class="bg-black-1 p-12 round-8">
				<y-radio :list="data.typeList" v-if="form.type==1" v-model="form.create_type" />
				<y-radio :list="data.textList" v-if="form.type==2" v-model="form.create_type" />
			</view>
			<view class="bg-black-1 p-12 round-8 text-white fs-15">
				<text>{{cretatTypeText}}</text>
				<y-radio :list="data.textTypeList" v-if='form.type==2' v-model="form.textType" @change="changeTextType"
					class="mt-8" title='图片来源'></y-radio>
				<y-upload v-model="tempUrl" v-if="form.create_type==1||isTextArtMode"></y-upload>
				<y-content v-if="form.create_type==2" v-model="form.qr_content"></y-content>
			</view>
			<view class="bg-black-1 px-12 pt-12 round-8 text-white grid-gap-12 fs-15 flex flex-column"
				style="padding-bottom: 150rpx;">
				<y-radio :list="data.modeList" v-model="form.engine" @change='changeModel' title="创作模式" />
				<view v-if='form.create_type=="textart"'>
					<text>渲染方式</text>
					<y-rendering-list :list='data.renderingList' v-model='form.textart_type'></y-rendering-list>
				</view>
				<view v-if="form.engine === 2">
					<text>描述词</text>
					<y-content v-model="form.prompt" placeholder="请输入描述词主体+运动，背景+运动...例如：美女用手带上墨镜，背景出现一道光"></y-content>
				</view>
				<y-slider v-model="iw"></y-slider>
				<y-radio :list="data.versionList" v-model="form.version" title="版本选择"
					v-if="form.type==1&&form.engine === 2" />
				<view v-if="form.engine==1">
					<text>{{form.type==1?'二维码风格':'选择模板'}}</text>
					<z-paging-mini ref="paging" use-page-scroll default-page-size="9" v-model="templateList"
						@query="getList">
						<y-template-list :list="templateList" @select='select'
							v-model='form.template_id'></y-template-list>
					</z-paging-mini>
				</view>
				<view v-if="form.engine === 2">
					<text>模型选择</text>
					<y-model-list :list='modelList' @change="selectModel" v-model="form.model_id"></y-model-list>
					<y-radio :list="data.proportionList" v-model="form.ar" title="比例选择" v-if='form.type==1' />
					<y-radio :list="data.ratioList" v-model="form.ratio" title="比例选择" v-if='form.type==2' />
				</view>
				<view v-if='form.type==1&&form.engine === 2'>
					<text>码眼选择</text>
					<view class="grid-columns-7 grid-gap-6 mt-8">
						<view v-for="(item,index) in WEBCONFIG.shape_list" :key="index" @click="form.shape=item.value"
							:class="form.shape==item.value?'border-blue ':'border-black-1 '"
							class="round-6 w-40 h-40 border-blod">
							<image class=" w-p-100 h-p-100 round-6" :src='item.url'></image>
						</view>

					</view>
				</view>
			</view>
		</view>
		<view class="position-fixed   vw-100 box-sizing" :style="`z-index: 99999;bottom:${bottom}px;padding:0px 80px;`">
			<view class="bg-blue w-p-100 text-center text-white py-13 round-30" @click="submit">立即生成({{points}}点)</view>
		</view>
	</view>

</template>

<script setup>
	import useZPaging from "@/uni_modules/z-paging-mini/components/z-paging-mini/js/hooks/useZPaging.js";
	import data from './data.js'
	import { computed, nextTick, onMounted, ref, watch } from 'vue';
	import { onLoad, onShow, onPageScroll, onReachBottom, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
	import { $http, $tool, $page } from '@/utils'
	import { useUserStore, useRefs, useWebConfigStore } from '@/stores'
	import { $interstitialAd, $videoAd } from '@/utils/ad'
	import system from "@/utils/system.js";
	const { WEBCONFIG } = useRefs(useWebConfigStore())
	const { USERINFO } = useRefs(useUserStore())
	const tempUrl = ref('')
	const time = ref(0)
	const height = ref(8)
	const bottom = ref(10)
	const paging = ref()
	const iw = ref(45)
	const form = ref({
		type: 1, //类型 1艺术二维码 2创意文字
		create_type: 1, //创作类型 1 图片 2自定义文字
		textType: 1,
		engine: 1, //引擎 1默认 2自定义
		iw: 0.45, //艺术度
		template_id: 0, //模型ID
		prompt: '', //提示词
		qr_content: '', //二维码内容
		version: 1, //版本
		ar: '1:1', //屏幕比例
		model_id: '', //模型ID
		image: '', //二维码图片
		textart_type: 1, //文字渲染模型
		shape: 'square', //码眼
		ratio: 1, //比例-艺术字
	})

	const queryForm = ref({ type: 'qrcode' })
	const modelList = ref([])
	const templateList = ref([])
	useZPaging(paging)
	onLoad(() => {
		height.value += uni.getSystemInfoSync().statusBarHeight
		// #ifdef H5
		bottom.value += 50
		console.log(uni.getSystemInfoSync())
		const script = document.createElement('script');
		script.type = "text/javascript";
		script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js'
		script.onload = () => {
			init()
		}
		document.body.appendChild(script)
		// #endif

		uni.$once('initConfig', () => {
			// #ifdef MP-WEIXIN
			if (WEBCONFIG.value?.weixin_interstitial_status == '1') {
				$interstitialAd.init(WEBCONFIG.value?.weixin_interstitial_ad_id)
				$interstitialAd.show()
			}
			if (WEBCONFIG.value.weixin_video_status == '1') {
				$videoAd.init(WEBCONFIG.value.weixin_video_ad_id, (e) => {
					time.value = 0
					ad()
				})
				$videoAd.show()
			}
			// #endif
		})

		getUser()
	})



	onShow(() => {
		let pages = getCurrentPages();
		let currentPage = pages[pages.length - 1];
		if (currentPage.$vm.url) {
			tempUrl.value = currentPage.$vm.url
		}
		// #ifdef H5
		$tool.replaceUrlParam('appid', system.appid());
		let user_id = USERINFO.value?.id
		if (user_id) {
			$tool.replaceUrlParam('user_id', user_id)
		}
		// #endif

	})
	const getUser = () => {
		const { setUserInfo, isLogin } = useUserStore()
		if (isLogin()) {
			$http.get('User/getUser').then(res => {
				setUserInfo(res.data)
			})
		} else {
			uni.showModal({
				title: '温馨提示',
				content: '请先登录',
				success(res) {
					if (res.confirm) {
						$page.open('/pages/user/login')
					}
				}
			})
		}
	}

	const init = () => {
		$http.get('Mp/getConfig').then(res => {
			wx.config({
				debug: false,
				appId: res.data.appId, //公众号
				timestamp: res.data.timestamp,
				nonceStr: res.data.nonceStr,
				signature: res.data.signature,
				jsApiList: res.data.jsApiList,
				openTagList: ['wx-open-launch-weapp']
			})
			wx.ready(function() {
				wx.updateAppMessageShareData({
					title: WEBCONFIG.value.share_title,
					desc: WEBCONFIG.value.share_title,
					link: res.data.url,
					imgUrl: WEBCONFIG.value.share_image,
					success: function() {},
					catch: (err) => {
						console.log(err)
					}
				})
			});
			wx.error(function(res) {
				console.log(res)
			});
		})
	}

	const isTextArtMode = computed(() => {
		return form.value.create_type === 'textart' || form.value.create_type === 'textshadow' || form.value
			.create_type === 'texthidden';
	})
	const cretatTypeText = computed(() => {
		if (form.value.type == 1) {
			if (form.value.create_type === 1) {
				return '二维码内容 （上传你的二维码）';
			}
			if (form.value.create_type === 2) {
				return '二维码内容';
			}
		}
		if (form.value.type == 2) {
			return '文字内容(处理成图片后上传)';
		}
		return '';
	})
	const points = computed(() => {
		const formData = form.value;
		let number = 0;

		const getPoints = (engine, templateId) => {
			if (engine === 1) {
				return templateList.value.find(item => item.id === templateId)?.points || 0;
			}
			return 0;
		};

		const getVersionPoints = (engine, version, createType) => {
			if (engine === 2) {
				const versionPointsMap = {
					1: WEBCONFIG.value?.v1_points,
					1.1: WEBCONFIG.value?.v1_1_points,
					2: WEBCONFIG.value?.v2_points,
					3: WEBCONFIG.value?.v3_points,
				};

				const createTypePointsMap = {
					textart: WEBCONFIG.value?.textart_points,
					textshadow: WEBCONFIG.value?.textshadow_points,
					texthidden: WEBCONFIG.value?.texthidden_points,
				};

				return version ? versionPointsMap[version] : createTypePointsMap[createType];
			}
			return 0;
		};

		if (formData.type === 1) {
			number = getPoints(formData.engine, formData.template_id);
			if (formData.engine === 2) {
				number = getVersionPoints(formData.engine, formData.version);
			}
		}

		if (formData.type === 2) {
			number = getPoints(formData.engine, formData.template_id);
			if (formData.engine === 2) {
				number = getVersionPoints(formData.engine, null, formData.create_type);
			}
		}
		return number;
	});


	watch(() => form.value.create_type, (n, o) => {
		if (form.value.type == 1) {
			getModel()
			return;
		}
		if (form.value.type == 2) {
			if (form.value.engine == 1) {
				queryForm.value.type = form.value.create_type
				paging.value.reload()
			} else {
				getModel(form.value.create_type)
			}
		}
	})

	const changeModel = () => {
		if (form.value.type == 1 && form.value.engine == 2) {
			getModel()
		}
		if (form.value.type == 2 && form.value.engine == 2) {
			getModel(form.value.create_type)
		}
	}


	const getModel = (type = 'qrcode') => {
		$http.get('Template/getModel', { type: type }).then(res => {
			nextTick(() => {
				modelList.value = res.data
			})
		})
	}


	const getList = (page, limit) => {
		$http.get('Template/getList', { page: page, limit: limit, ...queryForm.value }).then(res => {
			paging.value.complete(res.data)
			if (page == 1) {
				form.value.template_id = res.data[0].id
			}
		})
	}

	const select = (e) => {
		iw.value = e.iw * 100
	}

	const change = (e) => {
		if (e == 1) {
			form.value.create_type = 1
			queryForm.value.type = 'qrcode'
		}
		if (e == 2) {
			form.value.create_type = 'textart'
			queryForm.value.type = 'textart'
		}
		if (form.value.engine == 1) {
			paging.value.reload()
		}
		tempUrl.value = ''
	}

	const qrCode = async () => {
		let formData = { ...form.value, iw: iw.value / 100 };
		if (formData.create_type == 1 && tempUrl.value == '') {
			$tool.toast('请上传二维码');
			return;
		}
		if (formData.create_type == 1) {
			const res = await $http.upload('Upload/Upload', { filePath: tempUrl.value, name: 'file', is_hide: 1 });
			formData.image = res.data.url
		}

		if (formData.create_type == 2 && formData.qr_content == '') {
			$tool.toast('请填写二维码内容');
			return;
		}
		if (formData.engine == 1 && formData.template_id == 0) {
			$tool.toast('请选择模板');
			return;
		}

		if (formData.engine == 2) {
			if (formData.prompt == '') {
				$tool.toast('请输入描述词');
				return;
			}

			if (formData.model_id == 0) {
				$tool.toast('请选择模型');
				return;
			}

		}
		uni.showLoading({
			title: '任务提交中...'
		})
		$http.post('Works/createCode', formData).then(res => {
			$tool.toast("任务已提交");
			setTimeout(() => {
				$page.switch('/pages/works/index')
			}, 500)
		}).catch(() => uni.hideLoading())
	}


	const text = async () => {
		let formData = { ...form.value, iw: iw.value / 100 };
		if (tempUrl.value == '') {
			$tool.toast('请上传文字图片');
			return;
		}
		if (formData.engine == 1 && formData.template_id == 0) {
			$tool.toast('请选择模板');
			return;
		}
		if (formData.engine == 2) {
			if (formData.prompt == '') {
				$tool.toast('请输入描述词');
				return;
			}
			if (formData.model_id == 0) {
				$tool.toast('请选择模型');
				return;
			}

		}
		const res = await $http.upload('Upload/Upload', { filePath: tempUrl.value, name: 'file', is_hide: 1 });
		formData.image = res.data.url
		uni.showLoading({
			title: '任务提交中...'
		})
		$http.post('Works/createText', formData).then(res => {
			$tool.toast("任务已提交");
			setTimeout(() => {
				$page.switch('/pages/works/index')
			}, 500)
		}).catch(() => uni.hideLoading())
	}

	const submit = () => {
		const { isLogin } = useUserStore()
		if (!isLogin()) {
			uni.showModal({
				title: '温馨提示',
				content: '请先登录',
				success(res) {
					if (res.confirm) {
						$page.open('/pages/user/login')
					}
				}
			})
		}
		uni.showLoading({
			title: '生成中...',
			mask: true
		})
		if (form.value.type == 1) {
			qrCode()
		} else {
			text()
		}
	}


	const ad = () => {
		setTimeout(() => {
			time.value++
			if (time.value == 30) {
				$videoAd.show()
				time.value = 0
			} else {
				ad()
			}
		}, 1000)
	}


	const changeTextType = (e) => {
		if (e == 2) {
			$page.open('/pages/draw/index')
		}
	}

	//分享
	onShareTimeline(() => {
		let id = USERINFO.value.id || 0
		return {
			title: WEBCONFIG.value?.share_title || WEBCONFIG.value?.web_name || '',
			query: 'pages/index/index?user_id=' + id,
			imageUrl: WEBCONFIG.value?.share_image || ''
		}
	})

	onShareAppMessage(() => {
		let id = USERINFO.value.id || 0
		return {
			title: WEBCONFIG.value?.share_title || WEBCONFIG.value?.web_name || '',
			path: 'pages/index/index?user_id=' + id,
			imageUrl: WEBCONFIG.value?.share_image || ''
		}
	})
</script>

<style>
	page {
		background-color: #181818;
	}

	.border-box {
		border: 1px dashed #5A5A5A;
	}

	.bg {
		background: radial-gradient(circle at -30% -20%, #273c55 0%, transparent 45%);
		background-repeat: no-repeat;
		background-position: top left;
		/* #ifdef H5 */
		background-attachment: fixed;
		/* #endif */
	}
</style>